package com.fjc.authorcation;

import com.fjc.domain.Permission;
import com.fjc.domain.Role;
import com.fjc.domain.User;
import com.fjc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by fjc on 2018/9/24.
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        Set<Role> roles = userService.findUserRoleByUsername(username);
        Set<Permission> permissions = userService.findRolePermissionByRole(roles);
        Set<String> rolestr = new HashSet<>();
        Set<String> permissionStr = new HashSet<>();
        for (Role role:roles) {
            rolestr.add(role.getRole());
        }
        for (Permission permission:permissions) {
            permissionStr.add(permission.getPermission());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(rolestr);
        info.addStringPermissions(permissionStr);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.findUserByUsername(usernamePasswordToken.getUsername());
        if(user == null){
            return null;
        }else{
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getName());
            SecurityUtils.getSubject().getSession().setAttribute("userInfo",user);
            return info;
        }
    }
}
